<template>
  <el-row class="register-now">
    <el-col :span="24">
      <p class="header-style">
        绑定帐号
      </p>
    </el-col>
    <el-form ref="formRegister"
             :model="formRegister"
             label-width="80px"
             :rules="rules">
      <el-col :span="24">
        <el-form-item label="用户名"
                      prop="user_no">
          <el-input v-model="formRegister.user_no"
                    placeholder="请输入用户名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="formRegister.password"
                    type="password"
                    placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24"
              class="bottom-box">
        <el-button @click="onCancel('passwordLogin')">取消</el-button>
        <el-button type="primary"
                   @click="onBindFun('formRegister')">绑定</el-button>
      </el-col>
    </el-form>
  </el-row>
</template>

<script>
import { userPermissionApi } from "@/services/UserPermission";
import { LoginBindAccountApi } from '@/services/WorkBench';
var checkPwd = (rule, value, cb) => {
  //验证密码的正则表达式
  const regPwd =
    /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*)(?=.*[`~!@#$%^&*()_\-+=<>.?:"{}].*).{10,32}$/
  if (regPwd.test(value)) {
    return cb()
  }
  cb(new Error('密码需包含大小写字母、数字及特殊字符，长度在10-32位之间'))
}
export default {
  props: {
    onBindAccountFunc: Function,
    // user_type: Number
  },
  data () {
    return {
      code: '',
      unique_token: '',
      formRegister: {
        user_no: '',
        password: ''
      },
      rules: {
        user_no: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { required: true, validator: checkPwd, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    //返回
    onCancel (mode) {
      this.onBindAccountFunc(mode, '返回');//回调
      // this.code = '';
      this.unique_token = '';
      this.formRegister = this.$options.data().formRegister;
      this.$refs['formRegister'].resetFields();
    },
    // 根据系统编号和授权码获取key
    getKey () {
      let authCode = process.env.AUTH_CODE;
      userPermissionApi
        .getKey({
          data: {
            system_no: "industry",
            auth_code: authCode
          }
        })
        .then(
          res => {
            console.log(res, "get key");
            let data = res.data;
            if (data.key) {
              window.sessionStorage.setItem("platformKey", data.key);
            };
            this.login();
          },
          err => {
            console.log(err);
          }
        );
    },
    // 根据域名获取单位信息
    getCompanyByDomain () {
      let domain =
        location.host.indexOf("localhost") >= 0
          ? "dev_platform.ihibuilding.cn"
          : location.host;
      // let domain = 'dev_platform.ihibuilding.cn'
      userPermissionApi
        .getCompanyByDomain({
          data: {
            company_domain: domain
          }
        })
        .then(
          res => {
            console.log(res, "get company domain");
            window.localStorage.setItem(
              "companyInfo",
              JSON.stringify(res.data)
            );
            this.companyInfo = res.data;
            this.containerStyle = {
              backgroundImage: `url(${this.companyInfo.image_picture})`
            }
            // 设置页面title为接口返回的数据
            let title = document.getElementsByTagName("title");
            title[0].innerText = this.companyInfo.platform_name || this.companyInfo.company_name;
            // 如果设置了公司logo，就将浏览器标签页的icon修改为logo
            if (this.companyInfo.company_logo) {
              let logo = document.querySelector(".tab-icon");
              logo.href = this.companyInfo.company_logo;
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    login () {
      userPermissionApi
        .userThirdBind({
          data: {
            unique_token: this.unique_token,
            password: this.formRegister.password,
            user_no: this.formRegister.user_no,
            third_type: 2//第三方类型 确认后传2
          }
        })
        .then(
          res => {
            if (res.code === 0) {
              // this.$message.success("绑定成功");
              this.getCompanyByDomain()// 根据域名获取单位信息
              this.clearStorage(res.data);
              this.onBindAccountFunc('passwordLogin', '返回');//回调
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    // 获取用户权限
    getUserAuth (userId) {
      userPermissionApi
        .getUserAuth({
          data: {
            user_id: userId
          }
        })
        .then(
          res => {
            console.log(res, "get user auth");
            let userAuthList = res.data.list;
            if (userAuthList) {
              this.$store.dispatch("setUserAuth", res.data.list);
            };
            var hrefUrl = process.env.JUMP_TO_BIND_PAGE + "myCompany"
            // window.location.href = hrefUrl;
            top.location.href = hrefUrl;// 在顶层页面打开新页面
            this.$message.success("操作成功");
          },
          err => {
            console.log(err);
          }
        );
    },
    // 登录成功后清除旧数据，写入新数据
    clearStorage (data) {
      this.$store.state.switchCompId = 0;
      window.localStorage.clear();
      this.$store.dispatch("resetActiveTabsList", []);
      // window.sessionStorage.setItem("access_token", data.access_token);
      window.localStorage.setItem("access_token", data.access_token);
      window.localStorage.setItem(
        "companyInfo",
        JSON.stringify(this.companyInfo)
      );
      window.localStorage.setItem("user_id", data.user_id);
      window.localStorage.setItem("phone", data.phone);
      window.localStorage.setItem("comp_id", data.comp_id);
      // window.sessionStorage.setItem("access_token", data.access_token);
      window.localStorage.setItem("access_token", data.access_token);
      window.localStorage.setItem("userInfo", JSON.stringify(data));
      this.getUserAuth(data.user_id);
      // if (typeVal == '注册' || typeVal == '绑定') {

      // } else {
      // this.$message({
      //   type: "success",
      //   message: "绑定成功",
      //   offset: 60
      // });
      // }
    },
    //绑定
    onBindFun (data) {
      this.$refs[data].validate(valid => {
        if (valid) {
          // LoginBindAccountApi.getYesOrNoBind({//获取code
          //   params: {
          //     system_no: 'dm',
          //     type: 0,
          //     code: this.code
          //   }
          // }).then((res) => {
          // this.unique_token = res.data.unique_token;
          // if (res.code == 0) {
          this.getKey()
          // }
          // }).catch((error) => {
          //   console.log(error)
          // });
        }
      });
    },
    // getYesOrNoBind () {
    //   // LoginBindAccountApi.getYesOrNoBind({
    //   //   params: {
    //   //     system_no: 'dm',
    //   //     type: 0,
    //   //     code: (window.location.href.split('=')[1]).split('&')[0]
    //   //   }
    //   // }).then((res) => {
    //   //   this.unique_token = res.data.unique_token;
    //   //   if (res.code == 0) {
    //   //     this.getKey('noUserNo')
    //   //   } 
    //   // }).catch((error) => {
    //   //   console.log(error)
    //   // })
    // }
  },
  mounted () {
    this.unique_token = this.$route.query.unique_token == undefined ? '' : this.$route.query.unique_token;//获取code值  (window.location.href.split('=')[1]).split('&')[0]
    // this.$nextTick(() => {
    //   this.getYesOrNoBind();//获取code
    // });
    // console.log('window=', window, 'window.location=', window.location, 'window.location.href=', (window.location.href.split('=')[1]).split('&')[0])
  },
  created () {
    console.log('子组件user_type=', this.user_type)
  }
}
</script>

<style lang="scss" scoped>
.bottom-box {
  text-align: center;
}
.header-style {
  font-size: 18px;
  color: #000;
  text-align: left;
  font-weight: normal;
  margin-bottom: 20px;
}
.register-now {
  padding: 20px;
}
</style>